from threading import Thread
from time import sleep
import hashlib
import socket
import sys
import re
import os

# 取得本地IP地址
s_ip_i = 0
while s_ip_i<3:
    try:
        s_ip_i += 1
        s_ip = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s_ip.connect(("223.5.5.5",53))
        print(' > Here ', s_ip.getsockname()[0])
        s_ip.close()
        break
    except:
        s_ip_i += 1

# 保证在传输结束后，端口可复用
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
port = 1079
s.bind(('', port))

def main(a1=""):
    print(" > The contend will be casted")
    if a1 != "":
        input_all = a1
        print(input_all)
    else:
        try:
            import clipboard
        except:
            os.system("pip install clipboard")
            import clipboard
        try:
            input_all = clipboard.paste()
            print(input_all)
        except:
            print(" > Please end with space chars")
            input_all = []
            eachinput = input()
            while eachinput.isspace()==False:
                input_all.append(eachinput)
                eachinput = input()
            input_all = '\n'.join(input_all)
    # print(clipboard.paste().encode('utf-8'))
    # print(hashlib.md5(clipboard.paste().encode('utf-8')).hexdigest().encode('utf-8'))
    print(" > ? Connection", end='\r')

    s.listen(10)
    c, addr = s.accept()
    print(' > {} Connected'.format(addr))

    # 对接收者告知md5
    send_all = hashlib.md5(input_all.encode('utf-8')).hexdigest().encode('utf-8') + b'0x00' + input_all.encode('utf-8')
    c.send(send_all)
    s.close()

    print(" > Cast Done")
    # input()

if __name__ == "__main__":
    if len(sys.argv)>=2:
        main(sys.argv[1])
    else:
        main()
